package cn.ysym.tcsy;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.ysym.dao.OfflineShippingDao;
import cn.ysym.dao.OfflineStockDao;
import cn.ysym.dao.OfflineSumDao;
import cn.ysym.dao.SettingDao;
import cn.ysym.model.OfflineShipping;
import cn.ysym.model.OfflineStock;
import cn.ysym.model.OfflineSum;
import cn.ysym.model.Setting;
import cn.ysym.util.CommonUtil;
import cn.ysym.util.HttpUtil;

public class UploadDataActivity extends AppCompatActivity {

    @BindView(R.id.progressBarOnline)
    ProgressBar progressBar;
    @BindView(R.id.lvData)
    ListView lvData;
    @BindView(R.id.lvError)
    ListView lvError;
    @BindView(R.id.bOneDel)
    Button bOneDel;
    @BindView(R.id.bOneUp)
    Button bOneUp;
    @BindView(R.id.bAllDel)
    Button bAllDel;
    @BindView(R.id.bAllUp)
    Button bAllUp;
    private SettingDao settingDao;
    private OfflineSumDao offlineSumDao;
    private OfflineStockDao offlineStockDao;
    private OfflineShippingDao offlineShippingDao;
    private View curSelect;
    private int curSelectId = 0;
    private UpDataTask upDataTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_data);
        ButterKnife.bind(this); //绑定butterKnife插件
        setTitle("离线数据");

        settingDao = new SettingDao(this);
        offlineSumDao = new OfflineSumDao(this);
        offlineStockDao = new OfflineStockDao(this);
        offlineShippingDao = new OfflineShippingDao(this);

        lvData.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (curSelect != null) curSelect.setBackgroundColor(Color.TRANSPARENT);
                view.setBackgroundColor(Color.CYAN);
                curSelect = view;
                //当前选中数据id
                ListView listView = (ListView) parent;
                HashMap<String, Object> data = (HashMap<String, Object>) listView.getItemAtPosition(position);
                curSelectId = (Integer) data.get("id");
            }
        });
        loadData();

        bOneDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (curSelect != null) {
                    new AlertDialog.Builder(UploadDataActivity.this).setTitle("确认要删除所选数据吗？")
                            .setIcon(android.R.drawable.ic_dialog_alert)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    offlineSumDao.deleteById(curSelectId);
                                    loadData();
                                }
                            })
                            .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            }).show();
                } else {
                    Toast.makeText(getApplicationContext(), "请选择要删除的数据", Toast.LENGTH_SHORT).show();
                }
            }
        });

        bOneUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (curSelect != null) {
                    if (upDataTask == null) {
                        progressBar.setVisibility(View.VISIBLE);
                        upDataTask = new UpDataTask(curSelectId);
                        upDataTask.execute((Void) null);
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "请选择要上传的数据", Toast.LENGTH_SHORT).show();
                }
            }
        });

        bAllDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(UploadDataActivity.this).setTitle("确认要删除全部数据吗？")
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                offlineSumDao.deleteAll();
                                loadData();
                            }
                        })
                        .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();
            }
        });

        bAllUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (upDataTask == null) {
                    progressBar.setVisibility(View.VISIBLE);
                    upDataTask = new UpDataTask(0);
                    upDataTask.execute((Void) null);
                }
            }
        });

        Setting loginType = settingDao.query("loginType");
        if ("0".equals(loginType.getSettingValue())) {
            bOneUp.setEnabled(false);
            bAllUp.setEnabled(false);
        }
        //错误信息
    }

    private void loadData() {
        List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
        List<OfflineSum> oss = offlineSumDao.getList();
        for (OfflineSum model : oss) {
            HashMap<String, Object> item = new HashMap<String, Object>();
            item.put("id", model.getId());
            item.put("procDesc", model.getProcDesc());
            item.put("procNum", model.getProcNum());
            item.put("succNum", model.getUpSuccNum());
            item.put("failNum", model.getUpFailNum());
            data.add(item);
        }
        //创建SimpleAdapter适配器将数据绑定到item显示控件上
        SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.data_item,
                new String[]{"procDesc", "procNum", "succNum", "failNum"}, new int[]{R.id.tvProcDesc, R.id.tvProcNum, R.id.tvSuccNum, R.id.tvFailNum});
        lvData.setAdapter(adapter);
        curSelect = null;
    }

    public class UpDataTask extends AsyncTask<Void, Void, String> {
        private int sumId;

        public UpDataTask(int sumId) {
            this.sumId = sumId;
        }

        @Override
        protected String doInBackground(Void... params) {
            Setting userName = settingDao.query("userName");
            Setting sessionKey = settingDao.query("sessionKey");
            StringBuilder sbError = new StringBuilder();
            if (sumId > 0) {
                OfflineSum os = offlineSumDao.getById(sumId);
                List<OfflineStock> stocks = offlineStockDao.getUnUp(os.getId());
                for (OfflineStock stock : stocks) {
                    JSONObject req = new JSONObject();
                    try {
                        req.put("version", "2.3.180801.a.main");
                        req.put("account", userName.getSettingValue());
                        req.put("productId", stock.getProductId());
                        req.put("bigCode", stock.getBigCode());
                        req.put("code", stock.getCode());
                        req.put("virtualBig", stock.getVirtualBig());
                        req.put("scanTime", stock.getScanTime());
                        req.put("sign", HttpUtil.genSign(req, sessionKey.getSettingValue()));
                        String retStr = HttpUtil.postJson("upStockData.sdo", req.toString());
                        JSONObject retJson = new JSONObject(retStr);
                        if (retJson.getInt("result") == 1) {
                            os.setUpSuccNum(os.getUpSuccNum() + 1);
                            stock.setUpSucc("1");
                            offlineStockDao.update(stock);
                        } else {
                            if ("0".equals(stock.getUpSucc()))
                                os.setUpFailNum(os.getUpFailNum() + 1);
                            stock.setUpSucc("2");
                            offlineStockDao.update(stock);

                            if (sbError.length() > 0) sbError.append("|");
                            sbError.append(stock.getCode() + " " + retJson.getString("message"));
                        }
                    } catch (Exception e) {
                        Log.d("zqfw", e.getMessage());
                    }
                }

                List<OfflineShipping> shippings = offlineShippingDao.getUnUp(os.getId());
                for (OfflineShipping shipping : shippings) {
                    JSONObject req = new JSONObject();
                    try {
                        req.put("version", "2.3.180801.a.main");
                        req.put("account", userName.getSettingValue());
                        req.put("type", os.getProcType());
                        req.put("dealerId", shipping.getDealerId());
                        req.put("productId", shipping.getProductId());
                        req.put("shippingId", shipping.getShippingId());
                        req.put("promotionId", shipping.getPromotionId());
                        req.put("code", shipping.getCode());
                        req.put("virtualBig", shipping.getVirtualBig());
                        req.put("scanTime", shipping.getScanTime());
                        req.put("sign", HttpUtil.genSign(req, sessionKey.getSettingValue()));
                        String retStr = HttpUtil.postJson("upShippingData.sdo", req.toString());
                        JSONObject retJson = new JSONObject(retStr);
                        if (retJson.getInt("result") == 1) {
                            os.setUpSuccNum(os.getUpSuccNum() + 1);
                            shipping.setUpSucc("1");
                            offlineShippingDao.update(shipping);
                        } else {
                            if ("0".equals(shipping.getUpSucc()))
                                os.setUpFailNum(os.getUpFailNum() + 1);
                            shipping.setUpSucc("2");
                            offlineShippingDao.update(shipping);

                            if (sbError.length() > 0) sbError.append("|");
                            sbError.append(shipping.getCode() + " " + retJson.getString("message"));
                        }
                    } catch (Exception e) {
                        Log.d("zqfw", e.getMessage());
                    }
                }

                offlineSumDao.update(os);
            } else {
                List<OfflineSum> oss = offlineSumDao.getList();
                for (OfflineSum os : oss) {
                    List<OfflineStock> stocks = offlineStockDao.getUnUp(os.getId());
                    for (OfflineStock stock : stocks) {
                        JSONObject req = new JSONObject();
                        try {
                            req.put("version", "2.3.180801.a.main");
                            req.put("account", userName.getSettingValue());
                            req.put("productId", stock.getProductId());
                            req.put("bigCode", stock.getBigCode());
                            req.put("code", stock.getCode());
                            req.put("virtualBig", stock.getVirtualBig());
                            req.put("scanTime", stock.getScanTime());
                            req.put("sign", HttpUtil.genSign(req, sessionKey.getSettingValue()));
                            String retStr = HttpUtil.postJson("upStockData.sdo", req.toString());
                            JSONObject retJson = new JSONObject(retStr);
                            if (retJson.getInt("result") == 1) {
                                os.setUpSuccNum(os.getUpSuccNum() + 1);
                                stock.setUpSucc("1");
                                offlineStockDao.update(stock);
                            } else {
                                if ("0".equals(stock.getUpSucc()))
                                    os.setUpFailNum(os.getUpFailNum() + 1);
                                stock.setUpSucc("2");
                                offlineStockDao.update(stock);

                                if (sbError.length() > 0) sbError.append("|");
                                sbError.append(stock.getCode() + " " + retJson.getString("message"));
                            }
                        } catch (Exception e) {
                            Log.d("zqfw", e.getMessage());
                        }
                    }

                    List<OfflineShipping> shippings = offlineShippingDao.getUnUp(os.getId());
                    for (OfflineShipping shipping : shippings) {
                        JSONObject req = new JSONObject();
                        try {
                            req.put("version", "2.3.180801.a.main");
                            req.put("account", userName.getSettingValue());
                            req.put("type", os.getProcType());
                            req.put("dealerId", shipping.getDealerId());
                            req.put("productId", shipping.getProductId());
                            req.put("shippingId", shipping.getShippingId());
                            req.put("promotionId", shipping.getPromotionId());
                            req.put("code", shipping.getCode());
                            req.put("virtualBig", shipping.getVirtualBig());
                            req.put("scanTime", shipping.getScanTime());
                            req.put("sign", HttpUtil.genSign(req, sessionKey.getSettingValue()));
                            String retStr = HttpUtil.postJson("upShippingData.sdo", req.toString());
                            JSONObject retJson = new JSONObject(retStr);
                            if (retJson.getInt("result") == 1) {
                                os.setUpSuccNum(os.getUpSuccNum() + 1);
                                shipping.setUpSucc("1");
                                offlineShippingDao.update(shipping);
                            } else {
                                if ("0".equals(shipping.getUpSucc()))
                                    os.setUpFailNum(os.getUpFailNum() + 1);
                                shipping.setUpSucc("2");
                                offlineShippingDao.update(shipping);

                                if (sbError.length() > 0) sbError.append("|");
                                sbError.append(shipping.getCode() + " " + retJson.getString("message"));
                            }
                        } catch (Exception e) {
                            Log.d("zqfw", e.getMessage());
                        }
                    }

                    offlineSumDao.update(os);
                }
            }

            return sbError.toString();
        }

        @Override
        protected void onPostExecute(String errStr) {
            upDataTask = null;
            progressBar.setVisibility(View.GONE);
            loadData();
            //显示错误
            if (!CommonUtil.isEmpty(errStr)) {
                ArrayAdapter<String> errorAdapter = new ArrayAdapter<String>(UploadDataActivity.this, R.layout.list_view);
                String[] errs = errStr.split("\\|");
                for (String err : errs) errorAdapter.add(err);
                lvError.setAdapter(errorAdapter);
            }
        }

    }

}
